package com.baogu.factoryjob.controller;

import com.baogu.factoryjob.job.handler.SensorWarningJobHand;
import com.baogu.factoryjob.job.handler.SensordataJobHand;
import com.baogu.factoryjob.service.BaoGuDataService;
import com.baogu.factoryjob.util.DateUtils;
import com.baogu.model.common.HttpResult;
import com.baogu.model.job.ReUploadData;
import com.baogu.model.job.where.ReUploadDataWhere;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class AppController {

    @Autowired
    private BaoGuDataService baoGuDataService;
    @Autowired
    private SensordataJobHand sensordataJobHand;
    @Autowired
    private SensorWarningJobHand sensorWarningJobHand;

    @RequestMapping("/reUpLoadData")
    public HttpResult reUpLoadData(String id) throws ParseException {
        System.out.println("重新采集数据任务ID==>" + id);
        ReUploadDataWhere where = new ReUploadDataWhere();
        where.setId(id);
        ReUploadData reUploadData = baoGuDataService.getReUploadData(where);
        HttpResult result = new HttpResult();
        if(reUploadData == null){
            result.setCode("10001");
            result.setMsg("查询不到需要重新计算的数据");
            return result;
        }
        Long value = reUploadData.getEndTime().getTime() - reUploadData.getBeginTime().getTime();
        if(value < 0 ){
            result.setCode("10002");
            result.setMsg("结束时间晚于开始时间");
            return result;
        }
        try{
            sensordataJobHand.reUploadData(reUploadData);
            sensorWarningJobHand.reUploadData(reUploadData);
            where.setStatus(0);
            where.setFailReason("完成");
            result.setMsg("OK");
            result.setCode("00000");
        }catch (Exception e){
            where.setStatus(2);
            where.setFailReason("处理异常");
            result.setMsg("处理异常");
            result.setCode("10003");
            e.printStackTrace();
        } finally {
            where.setUpdateTime(new Date());
            baoGuDataService.updateReUploadData(where);
        }
        return result;
    }
}
